<?php
/**
 * 收款单增加分公司ID
 * @author angl
 */

date_default_timezone_set("Asia/Shanghai");
set_time_limit(0);
if (isset($_SERVER['REQUEST_URI'])) {
    die('error');
}

if (!defined('API_ROOT_PATH')) {
    define('API_ROOT_PATH', dirname(__FILE__));
}

require(API_ROOT_PATH . '/../inc/common.php');
require(API_ROOT_PATH . '/../inc/Config.php');
require(API_ROOT_PATH . '/../inc/MysqliDb.php');

//初始化数据库链接
function init_db()
{
    $db = new MysqliDb ([
        'host' => MYSQLDB,
        'username' => MYSQLDB_USER,
        'password' => MYSQLDB_PWD,
        'db' => MYSQLDB_DATABASE,
        'port' => 3306,
        'prefix' => 'au_',
        'charset' => 'utf8'
    ]);
    return $db;
}

$db = init_db();
$last_id = 0;
$counter = 0;

while (true){
    $list = $db->where('id',$last_id,">")->get('collection', 2000);
    if(empty($list)){
        logUtil("{$counter} 条数据处理完成！");
        exit;
    }
    foreach ($list as $key=>$item){
        $carId = 0;
        $branchId = 0;
        if(in_array($item['payment_type'],[1,2,3,4])){
            $carId = getCarIdByOrder($item['id']);
        }elseif ($item['payment_type']==6 || $item['payment_type']==7 || $item['payment_type']==8 || $item['payment_type']==10){
            if($item['refer']==0){
                $carId = getCarIdByChange($item['id']);
            }else{
                $refundCarInfo = $db->where('collection_id_car',$item['id'])->orWhere('collection_id',$item['id'])->getOne("refund_car");
                $carId = $refundCarInfo['car_id'];
            }
        }

        $branchId = getBranchIdByCarId($carId);
        $res = $db->where('id',$item['id'])->update('collection',[
            'branch_id'=>$branchId,
            'update_time'=>$item['update_time'],
        ]);
        if(!$res){
            logUtil("收款单 {$item['id']} 处理完成");
        }else{
            logUtil("收款单 {$item['id']} 处理完成");
        }

        $last_id = $item['id'];
        $counter++;
    }
}

logUtil($counter." 条数据处理完成","INFO");

function getCarIdByOrder($collectionId)
{
    global $db;
    $orderCollection = $db->where('collection_id',$collectionId)->getOne("order_collections");
    $orderInfo = $db->where("order_id",$orderCollection['order_id'])->getOne("order");
    return $orderInfo['car_id'];
}

function getCarIdByChange($collectionId){
    global $db;
    $changeCollection = $db->where('collection_id',$collectionId)->getOne("change_collection");
    $changeInfo = $db->where("mid",$changeCollection['change_id'])->getOne("modify_list");
    $carSourceInfo = $db->where("sid",$changeInfo['sid'])->getOne("car_source");
    return $carSourceInfo['max_car_id'];
}

function getBranchIdByCarId($carId)
{
    global $db;
    $carInfo = $db->where('car_id',$carId)->getOne('cars');
    $branchInfo = $db->where("city_code",$carInfo['location_area'])->getOne("branch_city");
    return $branchInfo['branch_id'];
}
